using FytSoa.Application.Erp.Param;
using FytSoa.Common.Extensions;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-采购退货产品详细服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpPurchaseReturnInfoService : IApplicationService 
{
    private readonly SugarRepository<ErpPurchaseReturnInfo> _thisRepository;
    public ErpPurchaseReturnInfoService(SugarRepository<ErpPurchaseReturnInfo> thisRepository)
    {
        _thisRepository = thisRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpPurchaseReturnInfoDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ErpPurchaseReturnInfoDto>>();
    }
    
    /// <summary>
    /// 根据采购查询采购订单商品信息
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpPurchaseReturnInfoDto>> GetListAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id!=0,m=>m.ReturnId==param.Id)
            .Includes(m=>m.Product)
            .OrderByDescending(m=>m.Id)
            .ToListAsync();
        return query.Adapt<List<ErpPurchaseReturnInfoDto>>();
    }
    
    
    /// <summary>
    /// 根据退单信息查询商品列表
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpProductReturnDto>> GetByOrderAsync(PurchaseOrderSearchParam param)
    {
        var product = await _thisRepository.GetListAsync(m => m.ReturnId == param.Id);
        var productIds = product.Select(m => m.ProductId).ToList();
        #region 判断出库 仓库是否有当前产品

        var warehouseProductRepository = _thisRepository.ChangeRepository<SugarRepository<ErpWarehouseProduct>>();
        var warehouseProduct = await warehouseProductRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(param.ProductIds),m=>param.ProductIds.StrToListLong().Contains(m.Id))
            .WhereIF(param.WarehouseId!=0,m=>m.WarehouseId==param.WarehouseId)
            .ToListAsync();
        //判断仓库中产品是否存在
        if (warehouseProduct.Count==0 && param.WarehouseId!=0)
        {
            throw new BusinessException("当前仓库中没有符合出库的产品~");
        }
        #endregion
        var productRepository = _thisRepository.ChangeRepository<SugarRepository<ErpProduct>>();
        var query = await productRepository.AsQueryable()
            .WhereIF(string.IsNullOrEmpty(param.ProductIds),m=>productIds.Contains(m.Id))
            .WhereIF(!string.IsNullOrEmpty(param.ProductIds),m=>param.ProductIds.StrToListLong().Contains(m.Id))
            .WhereIF(!string.IsNullOrEmpty(param.TypeId),m=>m.TypeId==long.Parse(param.TypeId))
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Name.Contains(param.Key))
            .Includes(m=>m.Type)
            .Includes(m=>m.Unit)
            .Includes(m=>m.Employee)
            .Includes(m=>m.Supplier)
            .OrderByDescending(m=>m.Id)
            .ToListAsync();
        var result= query.Adapt<List<ErpProductReturnDto>>();
        foreach (var item in result)
        {
            var model = product.FirstOrDefault(m => m.ProductId == item.Id);
            var warehouseProductModel = warehouseProduct.FirstOrDefault(m => m.ProductId == item.Id);
            if (model == null) continue;
            item.Count = warehouseProductModel!.Count;
            item.Price = model.Amount;
            item.IsOutStock = model.IsOutStock;
        }
        return result;
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpPurchaseReturnInfoDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ErpPurchaseReturnInfoDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(List<ErpPurchaseReturnInfoDto> model)
    {
        var returnId = model.FirstOrDefault().ReturnId;
        await _thisRepository.DeleteAsync(m => m.ReturnId == returnId);
        await _thisRepository.InsertRangeAsync(model.Adapt<List<ErpPurchaseReturnInfo>>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ErpPurchaseReturnInfoDto model) =>
        await _thisRepository.UpdateAsync(model.Adapt<ErpPurchaseReturnInfo>());

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
